/**
 * @description tabsBar标签页逻辑，如无必要请勿修改
 */
import { defineStore } from 'pinia'
import type { tabsState } from '@/types/stores/tabs'
import { local } from '@/utils/storage'
export const useTabsStore = defineStore('tabs', {
  state: (): tabsState => ({
    locks: [],
    currrenName: '',
    visitedRoutes: [],
    levelOne: -1
  }),
  getters: {
    getCurrenName: (state: any) => state.currrenName,
    getLocaks: (state: any) => state.locks,
    getVisitedRoutes: (state: any) => state.visitedRoutes,
    getHistory: (state: any) => {
      return state.visitedRoutes.filter((el: any) => {
        return !el.meta.isFarth
      })
    }
  },
  actions: {
    /**
     * @description 自动添加路由缓存
     * @param {*} from
     * @param {*} to
     * @returns
     */
    addVisitedRoute(from: any, to: any) {
      if (!to.meta.isPage) {
        this.setCurrenName(to.name)
        if (to.matched.length >= 3) {
          const forthInfo = to.matched.at(-2)
          forthInfo.meta.isFarth = true
          this.visitedRoutes = [
            {
              name: forthInfo.name,
              meta: forthInfo.meta
            },
            {
              name: to.name,
              meta: to.meta
            }
          ]
        } else {
          this.visitedRoutes = [
            {
              name: to.name,
              meta: to.meta
            }
          ]
        }
      } else {
        if (!this.currrenName) {
          const localName: any = localStorage.getItem('currenName')
          if (localName) {
            this.currrenName = localName
          }
        }
        const index = this.visitedRoutes.findIndex(
          (el: any) => el.name === to.name
        )
        if (index >= 0) {
          this.visitedRoutes = this.visitedRoutes.filter(
            (el: any, n: number) => {
              return n <= index
            }
          )
        } else {
          this.visitedRoutes.push({
            name: to.name,
            meta: to.meta
          })
        }
      }
    },
    setCurrenName(name: string) {
      local.set('currenName', name)
      this.currrenName = name
    },
    /**
     * @description 解锁分组
     * @param {*} index
     * @returns
     */
    unlock(index: number) {
      this.visitedRoutes = this.locks[index].childer
      this.locks.splice(index, 1)
    }
  }
})
